<!DOCTYPE html>
<html lang="en-US">
  <head>
    


  <meta http-equiv="Content-Security-Policy" content="default-src 'self' https: 'unsafe-inline' 'unsafe-eval'; worker-src 'self' blob:; connect-src 'self' https://cdn.jsdelivr.net wss: data:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'">


    <meta name="generator" content="Hugo 0.54.0">
    <meta charset="utf-8">
    <script src="https://use.fontawesome.com/0ae8a400c3.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Running ELF executables from memory | TMZ Lair - Underground Coding</title>
    <meta name="description" content="Executing ELF binary files from memory with memfd_create syscall">
    <meta name="keywords" content="linux, elf, malware, assembly, golang, syscall, injection, virus">
    
    
    
    
    <meta property="og:title" content="Running ELF executables from memory" />
<meta property="og:description" content="Executing ELF binary files from memory with memfd_create syscall" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://www.guitmz.com/running-elf-from-memory/" />

<meta property="og:image" content="https://i.imgur.com/xtHTBhI.png" />
<meta property="article:published_time" content="2019-03-27T14:01:50&#43;02:00"/>
<meta property="article:modified_time" content="2019-03-27T14:01:50&#43;02:00"/>

    <meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://i.imgur.com/xtHTBhI.png"/>

<meta name="twitter:title" content="Running ELF executables from memory"/>
<meta name="twitter:description" content="Executing ELF binary files from memory with memfd_create syscall"/>

    




    

    
    
  <meta name="referrer" content="same-origin">


    
    
    <script integrity="sha512-2t0yyNrUdtn9WGIoBVxq5vtoJQYfoDQDbqRPpOb75f1hiL39DGLdJKDrGP60fBhXfrFeKyVhzWJvHvLgln/ElA==">/*! Fetch Inject v2.0.4 | Copyright (C) Josh Habdas <jhabdas@protonmail.com> (https://habd.as) | @license Zlib */
var fetchInject=function(){"use strict";const e=function(e,t,r,n,o,c,i){c=t.createElement(r),i=t.getElementsByTagName(r)[0],c.appendChild(t.createTextNode(n.text)),c.onload=o(n),i?i.parentNode.insertBefore(c,i):t.head.appendChild(c)};return function(t,r){if(!arguments.length)return Promise.reject(new ReferenceError("Failed to execute 'fetchInject': 1 argument required but only 0 present."));if(arguments[0]&&arguments[0].constructor!==Array)return Promise.reject(new TypeError("Failed to execute 'fetchInject': argument 1 must be of type 'Array'."));if(arguments[1]&&arguments[1].constructor!==Promise)return Promise.reject(new TypeError("Failed to execute 'fetchInject': argument 2 must be of type 'Promise'."));const n=[],o=r?[].concat(r):[],c=[];return t.forEach(e=>o.push(window.fetch(e).then(e=>[e.clone().text(),e.blob()]).then(e=>Promise.all(e).then(e=>{n.push({text:e[0],blob:e[1]})})))),Promise.all(o).then(()=>(n.forEach(t=>{c.push({then:r=>{t.blob.type.includes("text/css")?e(window,document,"style",t,r):e(window,document,"script",t,r)}})}),Promise.all(c)))}}();
</script>
    <script integrity="sha512-hno7WeTIciCJSjg/myjyK30HYkrcGCVwo4g4SpUalvrs3r2lS7bPNIQwbCNypKbg7BZ1sA4AsGnk6Gq4NOKpGA==">fetchInject(["/js/lazysizes.min.js"]);
</script>
    


  
  
  
  
    

  <meta title="mod:voyeur" content="status:enabled">
  <script>
  (function(f, a, t, h, o, m){
    a[h]=a[h]||function(){
      (a[h].q=a[h].q||[]).push(arguments)
    };
    o=f.createElement('script'),
    m=f.getElementsByTagName('script')[0];
    o.async=1; o.src=t; o.id='fathom-script';
    m.parentNode.insertBefore(o,m)
  })(document, window, 'https:\/\/stats.guitmz.com/tracker.js', 'fathom');
  fathom('trackPageview');
  </script>


  


    
    <link rel="canonical" href="https://www.guitmz.com/running-elf-from-memory/">
    
    
    <link rel="icon" sizes="any" href="data:image/svg+xml,%3Csvg%20viewBox='0%200%2046%2045'%20xmlns='http://www.w3.org/2000/svg'%3E%3Ctitle%3EAfter%20Dark%3C/title%3E%3Cpath%20d='M.708%2045L23%20.416%2045.292%2045H.708zM35%2038L23%2019%2011%2038h24z'%20fill='lime'/%3E%3C/svg%3E">

    

  
  
  
  
  
  
  
    
      
        <style>html{font-size:12px}*{box-sizing:border-box;text-rendering:geometricPrecision}body{font-size:1rem;line-height:1.5rem;margin:0;font-family:Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;word-wrap:break-word}h1,h2,h3,h4,h5,h6{line-height:1.3em}fieldset{border:none;padding:0;margin:0}pre{padding:2rem;margin:1.75rem 0;background-color:#fff;border:1px solid #ccc;overflow:auto}code[class*=language-],pre[class*=language-],pre code{font-weight:100;text-shadow:none;margin:1.75rem 0}a{cursor:pointer;color:#43a047;text-decoration:none;border-bottom:1px solid #43a047}a:hover{background-color:#43a047;color:#fff}.grid{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap}.grid.\-top{-ms-flex-align:start;align-items:flex-start}.grid.\-middle{-ms-flex-align:center;align-items:center}.grid.\-bottom{-ms-flex-align:end;align-items:flex-end}.grid.\-stretch{-ms-flex-align:stretch;align-items:stretch}.grid.\-baseline{-ms-flex-align:baseline;align-items:baseline}.grid.\-left{-ms-flex-pack:start;justify-content:flex-start}.grid.\-center{-ms-flex-pack:center;justify-content:center}.grid.\-right{-ms-flex-pack:end;justify-content:flex-end}.grid.\-between{-ms-flex-pack:justify;justify-content:space-between}.grid.\-around{-ms-flex-pack:distribute;justify-content:space-around}.cell{-ms-flex:1;flex:1;box-sizing:border-box}@media screen and (min-width:768px){.cell.\-1of12{-ms-flex:0 0 8.33333%;flex:0 0 8.33333%}.cell.\-2of12{-ms-flex:0 0 16.66667%;flex:0 0 16.66667%}.cell.\-3of12{-ms-flex:0 0 25%;flex:0 0 25%}.cell.\-4of12{-ms-flex:0 0 33.33333%;flex:0 0 33.33333%}.cell.\-5of12{-ms-flex:0 0 41.66667%;flex:0 0 41.66667%}.cell.\-6of12{-ms-flex:0 0 50%;flex:0 0 50%}.cell.\-7of12{-ms-flex:0 0 58.33333%;flex:0 0 58.33333%}.cell.\-8of12{-ms-flex:0 0 66.66667%;flex:0 0 66.66667%}.cell.\-9of12{-ms-flex:0 0 75%;flex:0 0 75%}.cell.\-10of12{-ms-flex:0 0 83.33333%;flex:0 0 83.33333%}.cell.\-11of12{-ms-flex:0 0 91.66667%;flex:0 0 91.66667%}}@media screen and (max-width:768px){.grid{-ms-flex-direction:column;flex-direction:column}.cell{-ms-flex:0 0 auto;flex:0 0 auto}}.hack,.hack blockquote,.hack code,.hack em,.hack h1,.hack h2,.hack h3,.hack h4,.hack h5,.hack h6,.hack strong{font-size:1rem;font-style:normal;font-family:Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif}.hack blockquote,.hack code,.hack em,.hack strong{line-height:20px}.hack blockquote,.hack code,.hack footer,.hack h1,.hack h2,.hack h3,.hack h4,.hack h5,.hack h6,.hack header,.hack li,.hack ol,.hack p,.hack section,.hack ul{float:none;margin:0;padding:0}.hack blockquote,.hack h1,.hack ol,.hack p,.hack ul{margin-top:20px;margin-bottom:20px}.hack h1{position:relative;display:inline-block;display:table-cell;padding:20px 0 30px;margin:0;overflow:hidden}.hack h1:after{content:"====================================================================================================";position:absolute;bottom:10px;left:0}.hack h1+*{margin-top:0}.hack h2,.hack h3,.hack h4,.hack h5,.hack h6{position:relative;margin-bottom:1.75rem}.hack h2:before,.hack h3:before,.hack h4:before,.hack h5:before,.hack h6:before{display:inline}.hack h2:before{content:"## "}.hack h3:before{content:"### "}.hack h4:before{content:"#### "}.hack h5:before{content:"##### "}.hack h6:before{content:"###### "}.hack li{position:relative;display:block;padding-left:20px}.hack li:after{position:absolute;top:0;left:0}.hack ul>li:after{content:"-"}.hack ol{counter-reset:a}.hack ol>li:after{content:counter(a) ".";counter-increment:a}.hack ol li:nth-child(n+10):after{left:-7px}.hack blockquote{position:relative;padding-left:17px;padding-left:2ch;overflow:hidden}.hack blockquote:after{content:">\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>\A>";white-space:pre;position:absolute;top:0;left:0;line-height:20px}.hack em:after,.hack em:before{content:"*";display:inline}.hack pre code:after,.hack pre code:before{content:""}.hack code{font-weight:700}.hack code:after,.hack code:before{content:"`";display:inline}.hack hr{position:relative;height:20px;overflow:hidden;border:0;margin:20px 0}.hack hr:after{content:"----------------------------------------------------------------------------------------------------";position:absolute;top:0;left:0;line-height:20px;width:100%;word-wrap:break-word}@-moz-document url-prefix(){.hack h1{display:block}}.hack-ones ol>li:after{content:"1."}p{margin:0 0 1.75rem}.container{max-width:70rem}.container,.container-fluid{margin:0 auto;padding:0 1rem}.inner{padding:1rem}.inner2x{padding:2rem}.pull-left{float:left}.pull-right{float:right}.progress-bar{height:8px;opacity:.8;background-color:#ccc;margin-top:12px}.progress-bar.progress-bar-show-percent{margin-top:38px}.progress-bar-filled{background-color:gray;height:100%;transition:width .3s ease;position:relative;width:0}.progress-bar-filled:before{content:"";border:6px solid transparent;border-top-color:gray;position:absolute;top:-12px;right:-6px}.progress-bar-filled:after{color:gray;content:attr(data-filled);display:block;font-size:12px;white-space:nowrap;position:absolute;border:6px solid transparent;top:-38px;right:0;-ms-transform:translateX(50%);transform:translateX(50%)}table{width:100%;border-collapse:collapse;margin:1.75rem 0;color:#778087}table td,table th{vertical-align:top;border:1px solid #ccc;line-height:15px;padding:10px}table thead th{font-size:10px}table tbody td:first-child{font-weight:700;color:#333}.form{width:30rem}.form-group{margin-bottom:1.75rem;overflow:auto}.form-group label{border-bottom:2px solid #ccc;color:#333;width:10rem;display:inline-block;height:38px;line-height:38px;padding:0;float:left;position:relative}.form-group.form-success label{color:#4caf50!important;border-color:#4caf50!important}.form-group.form-warning label{color:#ff9800!important;border-color:#ff9800!important}.form-group.form-error label{color:#f44336!important;border-color:#f44336!important}.form-control{outline:none;border:none;border-bottom:2px solid #ccc;padding:.5rem 0;width:20rem;height:38px;background-color:transparent}.form-control:focus{border-color:#555}.form-group.form-textarea label:after{position:absolute;content:"";width:2px;background-color:#fff;right:-2px;top:0;bottom:0}textarea.form-control{height:auto;resize:none;padding:1rem 0;border-bottom:2px solid #ccc;border-left:2px solid #ccc;padding:.5rem}select.form-control{border-radius:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;-ms-appearance:none}.help-block{color:#999;margin-top:.5rem}.form-actions{margin-bottom:1.75rem}.btn{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;cursor:pointer;outline:none;padding:.65rem 2rem;font-size:1rem;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;position:relative;z-index:1}.btn:active{box-shadow:inset 0 1px 3px rgba(0,0,0,.12)}.btn.btn-ghost{border-color:#757575;color:#757575;background-color:transparent}.btn.btn-ghost:focus,.btn.btn-ghost:hover{border-color:#424242;color:#424242;z-index:2}.btn.btn-ghost:hover{background-color:transparent}.btn-block{width:100%;display:-ms-flexbox;display:flex}.btn-default{color:#fff;background-color:#e0e0e0;border:1px solid #e0e0e0;color:#333}.btn-default:focus:not(.btn-ghost),.btn-default:hover{background-color:#dcdcdc;border-color:#dcdcdc}.btn-success{color:#fff;background-color:#4caf50;border:1px solid #4caf50}.btn-success:focus:not(.btn-ghost),.btn-success:hover{background-color:#43a047;border-color:#43a047}.btn-success.btn-ghost{border-color:#4caf50;color:#4caf50}.btn-success.btn-ghost:focus,.btn-success.btn-ghost:hover{border-color:#388e3c;color:#388e3c;z-index:2}.btn-error{color:#fff;background-color:#f44336;border:1px solid #f44336}.btn-error:focus:not(.btn-ghost),.btn-error:hover{background-color:#e53935;border-color:#e53935}.btn-error.btn-ghost{border-color:#f44336;color:#f44336}.btn-error.btn-ghost:focus,.btn-error.btn-ghost:hover{border-color:#d32f2f;color:#d32f2f;z-index:2}.btn-warning{color:#fff;background-color:#ff9800;border:1px solid #ff9800}.btn-warning:focus:not(.btn-ghost),.btn-warning:hover{background-color:#fb8c00;border-color:#fb8c00}.btn-warning.btn-ghost{border-color:#ff9800;color:#ff9800}.btn-warning.btn-ghost:focus,.btn-warning.btn-ghost:hover{border-color:#f57c00;color:#f57c00;z-index:2}.btn-info{color:#fff;background-color:#00bcd4;border:1px solid #00bcd4}.btn-info:focus:not(.btn-ghost),.btn-info:hover{background-color:#00acc1;border-color:#00acc1}.btn-info.btn-ghost{border-color:#00bcd4;color:#00bcd4}.btn-info.btn-ghost:focus,.btn-info.btn-ghost:hover{border-color:#0097a7;color:#0097a7;z-index:2}.btn-primary{color:#fff;background-color:#2196f3;border:1px solid #2196f3}.btn-primary:focus:not(.btn-ghost),.btn-primary:hover{background-color:#1e88e5;border-color:#1e88e5}.btn-primary.btn-ghost{border-color:#2196f3;color:#2196f3}.btn-primary.btn-ghost:focus,.btn-primary.btn-ghost:hover{border-color:#1976d2;color:#1976d2;z-index:2}.btn-group{overflow:auto}.btn-group .btn{float:left}.btn-group .btn-ghost:not(:first-child){margin-left:-1px}.card{border:1px solid #ccc}.card .card-header{color:#333;text-align:center;background-color:#ddd;padding:.5rem 0}.alert{color:#ccc;padding:1rem;border:1px solid #ccc;margin-bottom:1.75rem}.alert-success{color:#4caf50;border-color:#4caf50}.alert-error{color:#f44336;border-color:#f44336}.alert-info{color:#00bcd4;border-color:#00bcd4}.alert-warning{color:#ff9800;border-color:#ff9800}.media:not(:last-child){margin-bottom:1.25rem}.media-left{padding-right:1rem}.media-left,.media-right{display:table-cell;vertical-align:top}.media-right{padding-left:1rem}.media-body{display:table-cell;vertical-align:top}.media-heading{font-size:1.16667rem;font-weight:700}.media-content{margin-top:.3rem}.avatarholder,.placeholder{background-color:#f0f0f0;text-align:center;color:#b9b9b9;font-size:1rem;border:1px solid #f0f0f0}.avatarholder{width:48px;height:48px;line-height:46px;font-size:2rem;background-size:cover;background-position:50%;background-repeat:no-repeat}.avatarholder.rounded{border-radius:33px}.loading{display:inline-block;content:"&nbsp;";height:20px;width:20px;margin:0 .5rem;animation:a .6s infinite linear;border:2px solid #e91e63;border-right-color:transparent;border-radius:50%}.btn .loading{margin-bottom:0;width:14px;height:14px}.btn div.loading{float:left}.alert .loading{margin-bottom:-5px}@keyframes a{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.menu{width:100%}.menu .menu-item{display:block;color:#616161;border-color:#616161}.menu .menu-item.active,.menu .menu-item:hover{color:#000;border-color:#000;background-color:transparent}@media screen and (max-width:768px){.form-group label{display:block;border-bottom:none;width:100%}.form-group.form-textarea label:after{display:none}.form-control{width:100%}textarea.form-control{border-left:none;padding:.5rem 0}pre::-webkit-scrollbar{height:3px}}@media screen and (max-width:480px){.form{width:100%}}
.dark-grey{background-color:#181818;color:#ccc}.dark-grey pre{background-color:#181818;padding:0;border:none}.dark-grey pre code{color:#00bcd4}.dark-grey h1 a,.dark-grey h2 a,.dark-grey h3 a,.dark-grey h4 a,.dark-grey h5 a{color:#ccc}.dark-grey code,.dark-grey strong{color:#fff}.dark-grey code{font-weight:100}.dark-grey table{color:#ccc}.dark-grey table td,.dark-grey table th{border-color:#444}.dark-grey table tbody td:first-child{color:#fff}.dark-grey .form-group label{color:#ccc;border-color:rgba(95,95,95,.78)}.dark-grey .form-group.form-textarea label:after{background-color:#181818}.dark-grey .form-control{color:#ccc;border-color:rgba(95,95,95,.78)}.dark-grey .form-control:focus{border-color:#ccc;color:#ccc}.dark-grey textarea.form-control{color:#ccc}.dark-grey .card{border-color:rgba(95,95,95,.78)}.dark-grey .card .card-header{background-color:transparent;color:#ccc;border-bottom:1px solid rgba(95,95,95,.78)}.dark-grey .btn.btn-ghost.btn-default{border-color:#ababab;color:#ababab}.dark-grey .btn.btn-ghost.btn-default:focus,.dark-grey .btn.btn-ghost.btn-default:hover{border-color:#9c9c9c;color:#9c9c9c;z-index:1}.dark-grey .btn.btn-ghost.btn-default:focus,.dark-grey .btn.btn-ghost.btn-default:hover{border-color:#e0e0e0;color:#e0e0e0}.dark-grey .btn.btn-ghost.btn-primary:focus,.dark-grey .btn.btn-ghost.btn-primary:hover{border-color:#64b5f6;color:#64b5f6}.dark-grey .btn.btn-ghost.btn-success:focus,.dark-grey .btn.btn-ghost.btn-success:hover{border-color:#81c784;color:#81c784}.dark-grey .btn.btn-ghost.btn-info:focus,.dark-grey .btn.btn-ghost.btn-info:hover{border-color:#4dd0e1;color:#4dd0e1}.dark-grey .btn.btn-ghost.btn-error:focus,.dark-grey .btn.btn-ghost.btn-error:hover{border-color:#e57373;color:#e57373}.dark-grey .btn.btn-ghost.btn-warning:focus,.dark-grey .btn.btn-ghost.btn-warning:hover{border-color:#ffb74d;color:#ffb74d}.dark-grey .avatarholder,.dark-grey .placeholder{background-color:transparent;border-color:#333}.dark-grey .menu .menu-item{color:#ccc;border-color:rgba(95,95,95,.78)}.dark-grey .menu .menu-item.active,.dark-grey .menu .menu-item:hover{color:#fff;border-color:#ccc}:root{scroll-behavior:smooth;--screen-size-small: 30em}@keyframes intro{0%{opacity:0}100%{opacity:1}}.blur-up{-webkit-filter:blur(5px);filter:blur(5px);transition:filter 400ms,-webkit-filter 400ms}.blur-up.lazyloaded{-webkit-filter:blur(0);filter:blur(0)}.hack .readmore{margin-bottom:2.2em}.responsive-iframe{position:relative;padding-bottom:56.25%;padding-top:25px;height:0}.responsive-iframe iframe{position:absolute;top:0;left:0;width:100%;height:100%}iframe{border:0}main,footer{animation:intro .3s both;animation-delay:.15s}header:first-of-type+details{margin-top:1rem}footer time[datetime$=M]:before{content:"\2013\0020"}body>footer p.muted{margin-bottom:0}@media only screen and (max-width:768px){footer time[datetime$=M]{display:none}}blockquote cite{display:block}blockquote cite::before{content:"\2014\00A0"}:target{filter:brightness(1.2)}:disabled{cursor:not-allowed}#search-app [v-cloak]{display:none}.hack li ul{margin:0}.hack ol li{padding-left:27px}.main{padding:20px 10px}input.form-control{border-radius:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;-ms-appearance:none}input.form-control,textarea.form-control,select.form-control,.help-block{font-size:initial}@media only screen and (max-width:768px){.help-block{font-size:unset}}html{font-size:13px}.hack .form input,.hack .form textarea,.hack .form button,.hack .form label{font-size:1rem}.hack .alert .highlight:first-of-type .chroma,.hack .card .highlight:first-of-type .chroma{margin-top:unset}.hack .alert .highlight:last-of-type .chroma,.hack .card .highlight:last-of-type .chroma{margin-bottom:unset}.hack blockquote,.hack blockquote:after{line-height:1.5}.hack figure{margin:unset}.hack figure a{border-bottom:none}.hack figure a:hover{background-color:inherit}article [itemprop=description]{margin-bottom:20px;margin-top:20px}article header img{width:100%;border-radius:3px}table td,table th{line-height:inherit}table a{border-bottom:unset}img{max-width:100%}@media only screen and (min-width:768px){html{font-size:16px;margin-left:calc(100vw - 100%)}.container{max-width:50rem}}a[rel*="external"]::after {
  content: " " url("data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20class='i-external'%20viewBox='0%200%2032%2032'%20width='14'%20height='14'%20fill='none'%20stroke='%23ff9800'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='9.38%'%3E%3Cpath%20d='M14%209%20L3%209%203%2029%2023%2029%2023%2018%20M18%204%20L28%204%2028%2014%20M28%204%20L14%2018'/%3E%3C/svg%3E");
}
nav a.active {
  background-color: #43a047;
  color: #fff;
}
a[itemprop="url"] {
  color: #ff9800;
}
a[itemprop="url"]:hover {
  color: #fff;
}
.muted, .help-block {
  opacity: 0.70;
}
.hack .muted,
.hack .help-block {
  color: #e0e0e0;
}

ul.social-icons {
  float: right;
  margin: 0;
  padding: 0;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  padding-inline-start: 40px;
  text-align: center;
  padding-top: 15px;
}

li.social-icons {
  display: inline-block;
  margin: 0 5px;
  list-style-type: circle;
}

a.social-icons {
  border-bottom: 0px;
  background-color: transparent;
  color: #ccc;
}

.highlight,pre.highlight{background:#282c34;color:#abb2bf}.highlight pre{background:#282c34;padding:1em;border:1px solid #ddd;background-color:#181818;box-shadow:5px 5px 5px #306734;}.highlight .ge{font-style:italic}.highlight .gs{font-weight:700}.highlight .ow{font-weight:700}.highlight .n,.highlight .nf,.highlight .nn,.highlight .o,.highlight .p{color:#abb2bf}.highlight .c,.highlight .c1,.highlight .cm,.highlight .cp,.highlight .cs{color:#5c6370;font-style:italic}.highlight .sr,.highlight .ss{color:#56b6c2}.highlight .k,.highlight .kc,.highlight .kd,.highlight .kn,.highlight .kp,.highlight .kr,.highlight .kt{color:#c678dd}.highlight .l,.highlight .ld,.highlight .s,.highlight .s1,.highlight .s2,.highlight .sb,.highlight .sc,.highlight .sd,.highlight .se,.highlight .sh,.highlight .si,.highlight .sx{color:#98c379}.highlight .nt,.highlight .nx,.highlight .vi{color:#e06c75}.highlight .il,.highlight .m,.highlight .mf,.highlight .mh,.highlight .mi,.highlight .mo,.highlight .na{color:#d19a66}.highlight .bp,.highlight .nb,.highlight .nc,.highlight .nd,.highlight .ne,.highlight .ni,.highlight .nl,.highlight .no,.highlight .nv,.highlight .py,.highlight .vc,.highlight .vg{color:#e5c07b}.highlight .err{color:#fff;background-color:#e05252}.highlight .gd{color:#e05252}.highlight .gi{color:#43d08a}.highlight .w{color:#f8f8f2}.highlight .cpf{color:#4146ff}.highlight .gu{color:#75715e}.highlight .lineno{color:#636d83;user-select:none}.highlight .hll{color:#abb2bf;background-color:#2c313a}.highlight .language-json .w+.s2{color:#e06c75}.highlight .language-json .kc{color:#56b6c2}
</style>
        


  
    <meta name="theme-color" content=#181818>
  



      
    
  


    
    
      <script integrity="sha512-ISTAV0GadOIz/NXXHOS+eCM0ysXVVHhQTlvA6LJxz/DeA5yIxm0Vqf5IE+WH0yuuXkayAKtoZkQ326nch5f/fg==">fetchInject(["/css/syntax.css"]);</script>
      <noscript>
        <link rel='stylesheet' href='https://d33wubrfki0l68.cloudfront.net/css/f3286ee8361fb56b8999bf51aea6a9a6b838e21e/css/syntax.css'/>
      </noscript>
    
  <script async defer data-website-id="f59c66c1-74d1-4f8b-9fcd-589ec2d06e21" src="https://umami.guitmz.com/umami.js"></script></head>
  
  
  
  <body class="dark dark-grey main container">
    <ul class="social-icons">
	<li class="social-icons"><a href="http://twitter.com/share?url=https%3a%2f%2fwww.guitmz.com%2frunning-elf-from-memory%2f&text=Running%20ELF%20executables%20from%20memory%20" target="_blank" class="social-icons"><i class="fa fa-twitter fa-lg"></i></a></li>
	<li class="social-icons"><a href="http://www.facebook.com/sharer.php?u=https%3a%2f%2fwww.guitmz.com%2frunning-elf-from-memory%2f" class="social-icons" target="_blank"><i class="fa fa-facebook fa-lg"></i></a></li>
	<li class="social-icons"><a href="http://reddit.com/submit?url=https%3a%2f%2fwww.guitmz.com%2frunning-elf-from-memory%2f&amp;title=Running%20ELF%20executables%20from%20memory" class="social-icons" target="_blank"><i class="fa fa-reddit-alien fa-lg"></i></a></li>
	<li class="social-icons"><a href="https://news.ycombinator.com/submitlink?u=https%3a%2f%2fwww.guitmz.com%2frunning-elf-from-memory%2f&amp;t=Running%20ELF%20executables%20from%20memory" class="social-icons" target="_blank"><i class="fa fa-hacker-news fa-lg"></i></a></li>
	<li class="social-icons"><a href="http://www.linkedin.com/shareArticle?mini=true&amp;url=https%3a%2f%2fwww.guitmz.com%2frunning-elf-from-memory%2f&amp;title=Running%20ELF%20executables%20from%20memory" class="social-icons" target="_blank"><i class="fa fa-linkedin fa-lg"></i></a></li>
	<li class="social-icons"><a href="mailto:?Subject=Running%20ELF%20executables%20from%20memory&amp;Body=https%3a%2f%2fwww.guitmz.com%2frunning-elf-from-memory%2f" class="social-icons" target="_blank"><i class="fa fa-envelope-o fa-lg"></i></a></li>
</ul>

    <header>
  

  
    
      
  <nav itemscope itemtype="https://schema.org/SiteNavigationElement">
    <meta itemprop="name" content="Main Menu">
    
      
      
        <a itemprop="url" href="/">Home</a>
      
    
      
      
        <a itemprop="url" class="active" href="/post/">Posts</a>
      
    
      
      
        <a itemprop="url" href="/about/">About</a>
      
    
      
      
        <a itemprop="url" href="/search/">Search</a>
      
    
  </nav>


    
  


</header>
    <main>
  <article itemscope itemtype="https://schema.org/BlogPosting">
    
<meta itemprop="name" content="Running ELF executables from memory">
<meta itemprop="description" content="Executing ELF binary files from memory with memfd_create syscall">


<meta itemprop="datePublished" content="2019-03-27T14:01:50&#43;02:00" />
<meta itemprop="dateModified" content="2019-03-27T14:01:50&#43;02:00" />
<meta itemprop="wordCount" content="1305">

  <meta itemprop="image" content="https://i.imgur.com/xtHTBhI.png">



<meta itemprop="keywords" content="linux,elf,malware,assembly,golang,syscall,injection,virus," />

    <header>
      <h1 itemprop="headline name">Running ELF executables from memory</h1>
      <p class="muted">
        <svg style="margin-bottom:-3px" class="i-clock" viewBox="0 0 32 32" width="16" height="16" fill="none" stroke="currentcolor" stroke-linecap="round" stroke-linejoin="round" stroke-width="6.25%">
  <circle cx="16" cy="16" r="14" />
  <path d="M16 8 L16 16 20 20" />
</svg>
<span>7 minute read</span>
<svg style="margin-bottom: -3px" class="i-edit" viewBox="0 0 32 32" width="16" height="16" fill="none" stroke="currentcolor" stroke-linecap="round" stroke-linejoin="round" stroke-width="6.25%">
  <path d="M30 7 L25 2 5 22 3 29 10 27 Z M21 6 L26 11 Z M5 22 L10 27 Z" />
</svg>

  Published: <time datetime="2019-03-27T14:01:50&#43;02:00">27 Mar, 2019</time>


      </p>
      
        <blockquote itemprop="description">Executing ELF binary files from memory with memfd_create syscall</blockquote>
      
      
    </header>
    
  <details>
    <summary>Table of Contents</summary>
    <nav id="TableOfContents">
<ul>
<li>
<ul>
<li><a href="#overview-and-code">Overview and code</a></li>
<li><a href="#see-it-in-action">See it in action</a></li>
</ul></li>
</ul>
</nav>
  </details>


    <div itemprop="articleBody">
      
      

<p><br>
Something that always fascinated me was running code directly from memory. From <a href="https://www.adlice.com/runpe-hide-code-behind-legit-process/">Process Hollowing</a> (aka RunPE) to <code>PTRACE</code> <a href="https://blog.xpnsec.com/linux-process-injection-aka-injecting-into-sshd-for-fun/">injection</a>. I had some success playing around with it in <code>C</code> in the past, without using any of the previous mentioned methods, but unfortunately the code is lost somewhere in the forums of <code>VXHeavens</code> (sadly no longer online) but the code was buggy and worked only with Linux 32bit systems (I wish I knew about <a href="http://man7.org/linux/man-pages/man3/shm_open.3.html">shm_open</a> back then, which is sort of an alternative for the syscall we are using in this post, mainly targeting older systems where <code>memfd_create</code> is not available).</p>

<h2 id="overview-and-code">Overview and code</h2>

<p>Recently, I have been trying to code in <code>assembly</code> a bit, I find it very interesting and I believe every developer should understand at least the basics of it. I chose <a href="https://flatassembler.net">FASM</a> as my assembler because I think it is very simple, powerful and I like its concepts (like same source, same output). More information about its design can be found <a href="https://flatassembler.net/docs.php?article=design">here</a>. Anyway, I have written a small tool, <code>memrun</code>, that allows you to run ELF files from memory using the <a href="http://man7.org/linux/man-pages/man2/memfd_create.2.html">memfd_create</a> syscall, which is available in Linux where kernel version is <code>&gt;= 3.17</code>.</p>

<p>What happens with <code>memfd_create</code> is that it acts like <code>malloc</code> syscall but will return a file descriptor that references an anonymous file (which does not exists in the disk) and we can pass it to <code>execve</code> and execute it from memory. There are a couple in-depth articles about it around the internet already so I will not get too deep into it. A nice one by <code>magisterquis</code> can be found at his <a href="https://magisterquis.github.io/2018/03/31/in-memory-only-elf-execution.html">page</a></p>

<p>The assembly code might look too big but there are some things we need to take care in this case that we don&rsquo;t need to when writing in a HLL like <code>Go</code> (as you can see in its example below). Also it&rsquo;s nice if you want to use the code for an exploit, you can just adjust the assembly instructions to your needs. Both examples are for <code>x86_64</code> only:</p>

<div class="highlight"><pre class="chroma"><code class="language-nasm" data-lang="nasm"><span class="nf">format</span> <span class="nv">ELF64</span> <span class="nv">executable</span> <span class="mi">3</span>

<span class="nf">include</span> <span class="s">&#34;struct.inc&#34;</span>
<span class="nf">include</span> <span class="s">&#34;utils.inc&#34;</span>

<span class="k">segment</span> <span class="nv">readable</span> <span class="nv">executable</span>
<span class="nf">entry</span> <span class="nv">start</span>

<span class="nl">start:</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; parsing command line arguments</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">pop</span>   <span class="nb">rcx</span>                       <span class="c1">; arg count</span>
  <span class="nf">cmp</span>   <span class="nb">rcx</span><span class="p">,</span> <span class="mi">3</span>                    <span class="c1">; needs to be at least two for the self program arg0 and target arg1</span>
  <span class="nf">jne</span>   <span class="nv">usage</span>                     <span class="c1">; exit 1 if not</span>

  <span class="nf">add</span>   <span class="nb">rsp</span><span class="p">,</span> <span class="mi">8</span>                    <span class="c1">; skips arg0</span>
  <span class="nf">pop</span>   <span class="nb">rsi</span>                       <span class="c1">; gets arg1</span>

  <span class="nf">mov</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="nv">sourcePath</span>
  <span class="nf">push</span>  <span class="nb">rsi</span>                       <span class="c1">; save rsi</span>
  <span class="nf">push</span>  <span class="nb">rdi</span>
  <span class="nf">call</span>  <span class="nv">strToVar</span>

  <span class="nf">pop</span>   <span class="nb">rsi</span>                       <span class="c1">; restore rsi</span>
  <span class="nf">pop</span>   <span class="nb">rdi</span>
  <span class="nf">mov</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="nv">targetProcessName</span>
  <span class="nf">pop</span>   <span class="nb">rsi</span>                       <span class="c1">; gets arg2</span>
  <span class="nf">push</span>  <span class="nb">rdi</span>
  <span class="nf">call</span>  <span class="nv">strToVar</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; opening source file for reading</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">mov</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="nv">sourcePath</span>           <span class="c1">; loads sourcePath to rdi</span>
  <span class="nf">xor</span>   <span class="nb">rsi</span><span class="p">,</span> <span class="nb">rsi</span>                  <span class="c1">; cleans rsi so open syscall doesnt try to use it as argument</span>
  <span class="nf">mov</span>   <span class="nb">rdx</span><span class="p">,</span> <span class="nv">O_RDONLY</span>             <span class="c1">; O_RDONLY</span>
  <span class="nf">mov</span>   <span class="nb">rax</span><span class="p">,</span> <span class="nv">SYS_OPEN</span>             <span class="c1">; open</span>
  <span class="nf">syscall</span>                         <span class="c1">; rax contains source fd (3)</span>
  <span class="nf">push</span>  <span class="nb">rax</span>                       <span class="c1">; saving rax with source fd</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; getting source file information to fstat struct</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">mov</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="nb">rax</span>                  <span class="c1">; load rax (source fd = 3) to rdi</span>
  <span class="nf">lea</span>   <span class="nb">rsi</span><span class="p">,</span> <span class="p">[</span><span class="nb">fs</span><span class="nv">tat</span><span class="p">]</span>              <span class="c1">; load fstat struct to rsi</span>
  <span class="nf">mov</span>   <span class="nb">rax</span><span class="p">,</span> <span class="nv">SYS_FSTAT</span>            <span class="c1">; sys_fstat</span>
  <span class="nf">syscall</span>                         <span class="c1">; fstat struct conntains file information</span>
  <span class="nf">mov</span>   <span class="nv">r12</span><span class="p">,</span> <span class="kt">qword</span><span class="p">[</span><span class="nb">rsi</span> <span class="o">+</span> <span class="mi">48</span><span class="p">]</span>      <span class="c1">; r12 contains file size in bytes (fstat.st_size)</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; creating memory map for source file</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">pop</span>   <span class="nb">rax</span>                        <span class="c1">; restore rax containing source fd</span>
  <span class="nf">mov</span>   <span class="nv">r8</span><span class="p">,</span> <span class="nb">rax</span>                    <span class="c1">; load r8 with source fd from rax</span>
  <span class="nf">mov</span>   <span class="nb">rax</span><span class="p">,</span> <span class="nv">SYS_MMAP</span>              <span class="c1">; mmap number</span>
  <span class="nf">mov</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="mi">0</span>                     <span class="c1">; operating system will choose mapping destination</span>
  <span class="nf">mov</span>   <span class="nb">rsi</span><span class="p">,</span> <span class="nv">r12</span>                   <span class="c1">; load rsi with page size from fstat.st_size in r12</span>
  <span class="nf">mov</span>   <span class="nb">rdx</span><span class="p">,</span> <span class="mh">0x1</span>                   <span class="c1">; new memory region will be marked read only</span>
  <span class="nf">mov</span>   <span class="nv">r10</span><span class="p">,</span> <span class="mh">0x2</span>                   <span class="c1">; pages will not be shared</span>
  <span class="nf">mov</span>   <span class="nv">r9</span><span class="p">,</span> <span class="mi">0</span>                      <span class="c1">; offset inside test.txt</span>
  <span class="nf">syscall</span>                          <span class="c1">; now rax will point to mapped location</span>
  <span class="nf">push</span>  <span class="nb">rax</span>                        <span class="c1">; saving rax with mmap address</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; close source file</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">mov</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="nv">r8</span>                   <span class="c1">; load rdi with source fd from r8</span>
  <span class="nf">mov</span>   <span class="nb">rax</span><span class="p">,</span> <span class="nv">SYS_CLOSE</span>            <span class="c1">; close source fd</span>
  <span class="nf">syscall</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; creating memory fd with empty name (&#34;&#34;)</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">lea</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="p">[</span><span class="nv">bogusName</span><span class="p">]</span>          <span class="c1">; empty string</span>
  <span class="nf">mov</span>   <span class="nb">rsi</span><span class="p">,</span> <span class="nv">MFD_CLOEXEC</span>          <span class="c1">; memfd mode</span>
  <span class="nf">mov</span>   <span class="nb">rax</span><span class="p">,</span> <span class="nv">SYS_MEMFD_CREATE</span>
  <span class="nf">syscall</span>                         <span class="c1">; memfd_create</span>
  <span class="nf">mov</span>   <span class="nb">rbx</span><span class="p">,</span> <span class="nb">rax</span>                  <span class="c1">; memfd fd from rax to rbx</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; writing memory map (source file) content to memory fd</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">pop</span>   <span class="nb">rax</span>                       <span class="c1">; restoring rax with mmap address</span>
  <span class="nf">mov</span>   <span class="nb">rdx</span><span class="p">,</span> <span class="nv">r12</span>                  <span class="c1">; rdx contains fstat.st_size from r12</span>
  <span class="nf">mov</span>   <span class="nb">rsi</span><span class="p">,</span> <span class="nb">rax</span>                  <span class="c1">; load rsi with mmap address</span>
  <span class="nf">mov</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="nb">rbx</span>                  <span class="c1">; load memfd fd from rbx into rdi</span>
  <span class="nf">mov</span>   <span class="nb">rax</span><span class="p">,</span> <span class="nv">SYS_WRITE</span>            <span class="c1">; write buf to memfd fd</span>
  <span class="nf">syscall</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; executing memory fd with targetProcessName</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">xor</span>   <span class="nb">rdx</span><span class="p">,</span> <span class="nb">rdx</span>
  <span class="nf">lea</span>   <span class="nb">rsi</span><span class="p">,</span> <span class="p">[</span><span class="nv">argv</span><span class="p">]</span>
  <span class="nf">lea</span>   <span class="nb">rdi</span><span class="p">,</span> <span class="p">[</span><span class="nv">fdPath</span><span class="p">]</span>
  <span class="nf">mov</span>   <span class="nb">rax</span><span class="p">,</span> <span class="nv">SYS_EXECVE</span>           <span class="c1">; execve the memfd fd in memory</span>
  <span class="nf">syscall</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; exit normally if everything works as expected</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
  <span class="nf">jmp</span>   <span class="nv">normal_exit</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="c1">; initialized data</span>
<span class="c1">;-----------------------------------------------------------------------------</span>
<span class="k">segment</span> <span class="nv">readable</span> <span class="nv">writable</span>
<span class="nf">fstat</span>             <span class="nv">STAT</span>
<span class="nf">usageMsg</span>          <span class="nv">db</span> <span class="s">&#34;Usage: memrun &lt;path_to_elf_file&gt; &lt;process_name&gt;&#34;</span><span class="p">,</span> <span class="mh">0xA</span><span class="p">,</span> <span class="mi">0</span>
<span class="nf">sourcePath</span>        <span class="nv">db</span> <span class="mi">256</span> <span class="nv">dup</span> <span class="mi">0</span>
<span class="nf">targetProcessName</span> <span class="nv">db</span> <span class="mi">256</span> <span class="nv">dup</span> <span class="mi">0</span>
<span class="nf">bogusName</span>         <span class="nv">db</span> <span class="s">&#34;&#34;</span><span class="p">,</span> <span class="mi">0</span>
<span class="nf">fdPath</span>            <span class="nv">db</span> <span class="s">&#34;/proc/self/fd/3&#34;</span><span class="p">,</span> <span class="mi">0</span>
<span class="nf">argv</span>              <span class="nv">dd</span> <span class="nv">targetProcessName</span></code></pre></div>

<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="kn">package</span> <span class="nx">main</span>

<span class="kn">import</span> <span class="p">(</span>
	<span class="s">&#34;fmt&#34;</span>
	<span class="s">&#34;io/ioutil&#34;</span>
	<span class="s">&#34;os&#34;</span>
	<span class="s">&#34;syscall&#34;</span>
	<span class="s">&#34;unsafe&#34;</span>
<span class="p">)</span>

<span class="c1">// the constant values below are valid for x86_64
</span><span class="c1"></span><span class="kd">const</span> <span class="p">(</span>
	<span class="nx">mfdCloexec</span>  <span class="p">=</span> <span class="mh">0x0001</span>
	<span class="nx">memfdCreate</span> <span class="p">=</span> <span class="mi">319</span>
<span class="p">)</span>

<span class="kd">func</span> <span class="nf">runFromMemory</span><span class="p">(</span><span class="nx">displayName</span> <span class="kt">string</span><span class="p">,</span> <span class="nx">filePath</span> <span class="kt">string</span><span class="p">)</span> <span class="p">{</span>
	<span class="nx">fdName</span> <span class="o">:=</span> <span class="s">&#34;&#34;</span> <span class="c1">// *string cannot be initialized
</span><span class="c1"></span>	<span class="nx">fd</span><span class="p">,</span> <span class="nx">_</span><span class="p">,</span> <span class="nx">_</span> <span class="o">:=</span> <span class="nx">syscall</span><span class="p">.</span><span class="nf">Syscall</span><span class="p">(</span><span class="nx">memfdCreate</span><span class="p">,</span> <span class="nb">uintptr</span><span class="p">(</span><span class="nx">unsafe</span><span class="p">.</span><span class="nf">Pointer</span><span class="p">(</span><span class="o">&amp;</span><span class="nx">fdName</span><span class="p">)),</span> <span class="nb">uintptr</span><span class="p">(</span><span class="nx">mfdCloexec</span><span class="p">),</span> <span class="mi">0</span><span class="p">)</span>

	<span class="nx">buffer</span><span class="p">,</span> <span class="nx">_</span> <span class="o">:=</span> <span class="nx">ioutil</span><span class="p">.</span><span class="nf">ReadFile</span><span class="p">(</span><span class="nx">filePath</span><span class="p">)</span>
	<span class="nx">_</span><span class="p">,</span> <span class="nx">_</span> <span class="p">=</span> <span class="nx">syscall</span><span class="p">.</span><span class="nf">Write</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="nx">fd</span><span class="p">),</span> <span class="nx">buffer</span><span class="p">)</span>

	<span class="nx">fdPath</span> <span class="o">:=</span> <span class="nx">fmt</span><span class="p">.</span><span class="nf">Sprintf</span><span class="p">(</span><span class="s">&#34;/proc/self/fd/%d&#34;</span><span class="p">,</span> <span class="nx">fd</span><span class="p">)</span>
	<span class="nx">_</span> <span class="p">=</span> <span class="nx">syscall</span><span class="p">.</span><span class="nf">Exec</span><span class="p">(</span><span class="nx">fdPath</span><span class="p">,</span> <span class="p">[]</span><span class="kt">string</span><span class="p">{</span><span class="nx">displayName</span><span class="p">},</span> <span class="kc">nil</span><span class="p">)</span>
<span class="p">}</span>

<span class="kd">func</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
	<span class="nx">lenArgs</span> <span class="o">:=</span> <span class="nb">len</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Args</span><span class="p">)</span>
	<span class="k">if</span> <span class="nx">lenArgs</span> <span class="p">&lt;</span> <span class="mi">3</span> <span class="o">||</span> <span class="nx">lenArgs</span> <span class="p">&gt;</span> <span class="mi">3</span> <span class="p">{</span>
		<span class="nx">fmt</span><span class="p">.</span><span class="nf">Println</span><span class="p">(</span><span class="s">&#34;Usage: memrun process_name elf_binary&#34;</span><span class="p">)</span>
		<span class="nx">os</span><span class="p">.</span><span class="nf">Exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
	<span class="p">}</span>

	<span class="nf">runFromMemory</span><span class="p">(</span><span class="nx">os</span><span class="p">.</span><span class="nx">Args</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="nx">os</span><span class="p">.</span><span class="nx">Args</span><span class="p">[</span><span class="mi">2</span><span class="p">])</span>
<span class="p">}</span></code></pre></div>

<p>The full code for both versions can be found in this repo: <a href="https://github.com/guitmz/memrun">https://github.com/guitmz/memrun</a></p>

<h2 id="see-it-in-action">See it in action</h2>

<p>Allow me to show it in action. Let&rsquo;s start by creating a simple target file in <code>C</code>, named <code>target.c</code>. The file will try to open itself for reading and if it can&rsquo;t, it will print a message forever every 5 seconds. We will execute it from memory:</p>

<div class="highlight"><pre class="chroma"><code class="language-c" data-lang="c"><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
</span><span class="cp">#include</span> <span class="cpf">&lt;unistd.h&gt;</span><span class="cp">
</span><span class="cp"></span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span> <span class="o">**</span><span class="n">argv</span><span class="p">)</span>
<span class="p">{</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">&#34;My process ID : %d</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">,</span> <span class="n">getpid</span><span class="p">());</span>

  <span class="n">FILE</span> <span class="o">*</span><span class="n">myself</span> <span class="o">=</span> <span class="n">fopen</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="s">&#34;r&#34;</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">myself</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">while</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
                <span class="n">printf</span><span class="p">(</span><span class="s">&#34;I can&#39;t find myself, I must be running from memory!</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">);</span>
                <span class="n">sleep</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span>
        <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">&#34;I am just a regular boring file being executed from the disk...</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">);</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span></code></pre></div>

<p>Now we build <code>target.c</code>:




<div class="alert ">
  
<pre>
$ gcc target.c -o target
</pre>

</div>

</p>

<p>We should also build our <code>FASM</code> or <code>Go</code> tool, I will use the assembly one here:




<div class="alert ">
  
<pre>
$ fasm memrun.asm
flat assembler  version 1.73.04  (16384 kilobytes memory, x64)
4 passes, 1221 bytes.
</pre>

</div>

</p>

<p>Running the file normally gives us this:




<div class="alert ">
  
<pre>
$ ./target
My process ID : 4944
I am just a regular boring file being executed from the disk...
</pre>

</div>

</p>

<p>But using <code>memrun</code> to run it will be totally different:




<div class="alert ">
  
<pre>
$ ./memrun target MASTER_HACKER_PROCESS_NAME_1337
My process ID : 4945
I can't find myself, I must be running from memory!
I can't find myself, I must be running from memory!
</pre>

</div>

</p>

<p>Furthermore, if you look for its pid with <code>ps</code> utility, this is what you get:




<div class="alert ">
  
<pre>
$ ps -f 4945
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
guitmz    4945  4842  0 15:31 pts/0    S+     0:00 MASTER_HACKER_PROCESS_NAME_1337
</pre>

</div>

</p>

<p>Finally, let&rsquo;s check the process directory:




<div class="alert ">
  
<pre>
$ ls -l /proc/4945/{cwd,exe}
lrwxrwxrwx 1 guitmz guitmz 0 Mar 27 15:38 /proc/4945/cwd -> /home/guitmz/memrun/assembly
lrwxrwxrwx 1 guitmz guitmz 0 Mar 27 15:38 /proc/4945/exe -> /memfd: (deleted)
</pre>

</div>

</p>

<p>Note the <code>/memfd: (deleted)</code> part, no actual file in disk for this process :)</p>

<p>For those who know, this can be an interesting technique to run stealthy binaries in Linux, you can go even further by giving it a proper name (like a real Linux process) and detach it from the <code>tty</code> and change its <code>cwd</code> with some simple approches. Tip: <code>fork</code> is your friend :)</p>

<p>TMZ</p>

    </div>
    	
      <article>	
        <div id="disqus_thread"></div>
<script type="application/javascript">
    var disqus_config = function () {
    
    
    
    };
    (function() {
        if (["localhost", "127.0.0.1"].indexOf(window.location.hostname) != -1) {
            document.getElementById('disqus_thread').innerHTML = 'Disqus comments not available by default when the website is previewed locally.';
            return;
        }
        var d = document, s = d.createElement('script'); s.async = true;
        s.src = '//' + "guitmz" + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>	
      </article>	
    
    <footer>
      <hr>
      <p>
  Published
  
    
      by <span itemprop="author">Guilherme Thomazi</span>
    
  
  <time itemprop="datePublished" datetime="2019-03-27T14:01:50&#43;02:00">
    27 Mar, 2019
  </time>
  
    in <span itemprop="articleSection"><a href="/categories/technology/">technology</a></span>
  
  
    and tagged <a rel="tag" href="/tags/assembly/">assembly</a>, <a rel="tag" href="/tags/elf/">elf</a>, <a rel="tag" href="/tags/golang/">golang</a>, <a rel="tag" href="/tags/injection/">injection</a>, <a rel="tag" href="/tags/linux/">linux</a>, <a rel="tag" href="/tags/malware/">malware</a>, <a rel="tag" href="/tags/syscall/">syscall</a> and <a rel="tag" href="/tags/virus/">virus</a>
  
  using <span itemprop="wordCount">1305</span> words.
</p>

      


  <aside>
    <header>Related Content</header>
    <ul>
      
        <li><a href="/linux-liora/">Linux.Liora: a Go virus</a>
        <time datetime="4M">4 minutes</time>
      
        <li><a href="/more-fun-with-elf-files-and-golang-code-caves/">More fun with ELF files and GoLang - Code Caves</a>
        <time datetime="2M">2 minutes</time>
      
        <li><a href="/linux-cephei-a-nim-virus/">Linux.Cephei: a Nim virus</a>
        <time datetime="3M">3 minutes</time>
      
        <li><a href="/having-fun-with-elf-files-and-golang/">Having fun with ELF files and GoLang</a>
        <time datetime="2M">2 minutes</time>
      
        <li><a href="/win32-liora-b/">Win32.Liora.B</a>
        <time datetime="5M">5 minutes</time>
      
        <li><a href="/vala-virus/">Linux.Zariche: a Vala virus</a>
        <time datetime="9M">9 minutes</time>
      
        <li><a href="/yet-another-weather-indicator/">Yet Another Weather Indicator</a>
        <time datetime="3M">3 minutes</time>
      
    </ul>
  </aside>


    </footer>
  </article>
</main>
    <footer>
  

  
  <small class="muted">
    This site does not use
    <svg aria-hidden="true" role="presentation" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="12" height="12"><path fill="currentColor" d="M510.52 255.82c-69.97-.85-126.47-57.69-126.47-127.86-70.17 0-127-56.49-127.86-126.45-27.26-4.14-55.13.3-79.72 12.82l-69.13 35.22a132.221 132.221 0 0 0-57.79 57.81l-35.1 68.88a132.645 132.645 0 0 0-12.82 80.95l12.08 76.27a132.521 132.521 0 0 0 37.16 72.96l54.77 54.76a132.036 132.036 0 0 0 72.71 37.06l76.71 12.15c27.51 4.36 55.7-.11 80.53-12.76l69.13-35.21a132.273 132.273 0 0 0 57.79-57.81l35.1-68.88c12.56-24.64 17.01-52.58 12.91-79.91zM176 368c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32zm32-160c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32zm160 128c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32z"></path></svg>
    cookies.
  </small>


</footer>
    
    
    
      
    
    <script>fetchInject([
        "https://cdn.jsdelivr.net/npm/baffle@0.3.6/dist/baffle.min.js"
      ]).then(() => {
        baffle(document.querySelector('h1')).start().reveal(1500);
      })
    </script>
  <!-- Fathom - beautiful, simple website analytics -->
<script src="https://cdn.usefathom.com/script.js" data-site="RLPWUPGQ" defer></script>
<!-- / Fathom --></body>
</html>
